import axios from "axios";

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // 从环境变量获取基础 API 地址
  timeout: 10000, // 请求超时时间
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    const token = localStorage.getItem("token");
    const expiresIn = localStorage.getItem("expiresIn");
    if (token && expiresIn && expiresIn > new Date().getTime()) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    const res = response.data;
    if (res.message) {
      ElMessage({
        message: res.message,
        type: "success",
        duration: 5 * 1000,
      });
    }
    return res;
  },
  (error) => {
    // 对响应错误做点什么
    if (error.response) {
      if (error.response.status == 429) {
        error.message = '你小子是手速也太快了，服务器妹妹都被你干冒烟了.'
      } else if (error.response.status == 401) {
        ElMessageBox.confirm("登录状态已过期，请重新登录", "系统提示", {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          localStorage.removeItem("token");
          window.location.href = "/";
        });
      }
    } else if (error.message.includes("timeout")) {
      error.message = "请求超时";
    } else if (error.message === "Network Error") {
      error.message = "网络错误，请检查网络连接";
    }
    ElMessage({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

const get = (url, params = {}, config = {}) => {
  return service({
    method: "get",
    url,
    params,
    ...config,
  });
};

const post = (url, data = {}, config = {}) => {
  return service({
    method: "post",
    url,
    data,
    ...config,
  });
};

const put = (url, data = {}, config = {}) => {
  return service({
    method: "put",
    url,
    data,
    ...config,
  });
};

const del = (url, params = {}, config = {}) => {
  return service({
    method: "delete",
    url,
    params,
    ...config,
  });
};

export default {
  get,
  post,
  put,
  del
};
